<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { Page, useVbenModal } from '@vben/common-ui';
import { ACTION_ICON, TableAction, useVbenVxeGrid, type VxeTableGridOptions } from '#/adapter/vxe-table';
import { useMagicKeys, whenever } from '@vueuse/core';
import { message } from 'ant-design-vue';
import { useTabs } from '@vben/hooks';

import { getInfoGroupPage, type InfoGroupApi } from '#/api/spa/group';
import { getInfoStoreWithGroupPage, type InfoStoreApi } from '#/api/spa/store';
import { getSiteList, type SiteApi } from '#/api/spa/site';
import { useGroupSwitchStore } from '#/stores/group-switch';
import { useStoreSwitchStore } from '#/stores/store-switch';
import { useSiteStore } from '#/stores/site';

const { closeOtherTabs, refreshTab } = useTabs();
const groupSwitchStore = useGroupSwitchStore();
const storeSwitchStore = useStoreSwitchStore();
const siteStore = useSiteStore();

defineOptions({
  name: 'ThreeLevelSwitch',
});

// 当前选中的集团、门店、站点
const selectedGroup = ref<InfoGroupApi.InfoGroup | null>(null);
const selectedStore = ref<InfoStoreApi.InfoStore | null>(null);
const selectedSite = ref<SiteApi.Site | null>(null);

// 当前切换级别：1-集团，2-门店，3-站点
const currentLevel = ref(1);

const keys = useMagicKeys();
whenever(keys['Alt+KeyG']!, () => {
  modalApi.open();
});

const [Modal, modalApi] = useVbenModal({
  draggable: true,
  overlayBlur: 5,
  footer: false,
  onCancel() {
    modalApi.close();
  },
});

// 集团列表
const [GroupGrid] = useVbenVxeGrid({
  gridOptions: {
    columns: [
      { field: 'groupCode', title: '集团编码', minWidth: 120 },
      { field: 'groupName', title: '集团名称', minWidth: 150 },
      { field: 'contactPerson', title: '联系人', minWidth: 100 },
      { field: 'contactPhone', title: '联系电话', minWidth: 120 },
      { field: 'address', title: '地址', minWidth: 200 },
      {
        title: '操作',
        width: 120,
        fixed: 'right',
        slots: { default: 'actions' },
      },
    ],
    height: 'auto',
    pagerConfig: { enabled: true },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getInfoGroupPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: { keyField: 'id', isHover: true },
  } as VxeTableGridOptions<InfoGroupApi.InfoGroup>,
});

// 门店列表
const [StoreGrid] = useVbenVxeGrid({
  gridOptions: {
    columns: [
      { field: 'storeCode', title: '门店编码', minWidth: 120 },
      { field: 'storeName', title: '门店名称', minWidth: 150 },
      { field: 'contactPerson', title: '联系人', minWidth: 100 },
      { field: 'contactPhone', title: '联系电话', minWidth: 120 },
      { field: 'address', title: '地址', minWidth: 200 },
      {
        title: '操作',
        width: 120,
        fixed: 'right',
        slots: { default: 'actions' },
      },
    ],
    height: 'auto',
    pagerConfig: { enabled: true },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getInfoStoreWithGroupPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            groupId: selectedGroup.value?.id,
            ...formValues,
          });
        },
      },
    },
    rowConfig: { keyField: 'id', isHover: true },
  } as VxeTableGridOptions<InfoStoreApi.InfoStore>,
});

// 站点列表
const [SiteGrid] = useVbenVxeGrid({
  gridOptions: {
    columns: [
      { field: 'site_name', title: '站点名称', minWidth: 150 },
      { field: 'site_domain', title: '站点域名', minWidth: 150 },
      { field: 'group_name', title: '所属集团', minWidth: 120 },
      { field: 'status_name', title: '状态', minWidth: 100 },
      { field: 'address', title: '地址', minWidth: 200 },
      {
        title: '操作',
        width: 120,
        fixed: 'right',
        slots: { default: 'actions' },
      },
    ],
    height: 'auto',
    pagerConfig: { enabled: true },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getSiteList({
            page: page.currentPage,
            limit: page.pageSize,
            group_id: selectedGroup.value?.id,
            ...formValues,
          });
        },
      },
    },
    rowConfig: { keyField: 'site_id', isHover: true },
  } as VxeTableGridOptions<SiteApi.Site>,
});

// 当前选中的信息显示
const currentInfo = computed(() => {
  const group = selectedGroup.value || groupSwitchStore.getCurrentGroup();
  const store = selectedStore.value || storeSwitchStore.getCurrentStore();
  const site = selectedSite.value || siteStore.getCurrentSiteInfo();
  
  return {
    group: group ? `${group.groupName} (${group.groupCode})` : '未选择集团',
    store: store ? `${store.storeName} (${store.storeCode})` : '未选择门店',
    site: site ? `${site.siteName} (${site.siteId})` : '未选择站点',
  };
});

// 切换集团
async function handleSelectGroup(group: InfoGroupApi.InfoGroup) {
  selectedGroup.value = group;
  selectedStore.value = null;
  selectedSite.value = null;
  currentLevel.value = 2;
  StoreGrid.query();
}

// 切换门店
async function handleSelectStore(store: InfoStoreApi.InfoStore) {
  selectedStore.value = store;
  selectedSite.value = null;
  currentLevel.value = 3;
  SiteGrid.query();
}

// 切换站点
async function handleSelectSite(site: SiteApi.Site) {
  selectedSite.value = site;
}

// 完成切换
async function handleCompleteSwitch() {
  try {
    if (selectedGroup.value) {
      groupSwitchStore.setCurrentGroup(selectedGroup.value);
    }
    if (selectedStore.value) {
      storeSwitchStore.setCurrentStore(selectedStore.value);
    }
    if (selectedSite.value) {
      siteStore.setCurrentSiteInfo({
        siteId: selectedSite.value.site_id,
        siteName: selectedSite.value.site_name,
        siteDomain: selectedSite.value.site_domain,
        groupId: selectedSite.value.group_id,
        groupName: selectedSite.value.group_name,
        status: selectedSite.value.status,
        statusName: selectedSite.value.status_name,
      });
    }
    
    await closeOtherTabs();
    await refreshTab();
    modalApi?.close();
    
    message.success('切换成功！');
  } catch (error) {
    console.error('切换失败:', error);
    message.error('切换失败，请重试');
  }
}

// 返回上一级
function goBack() {
  if (currentLevel.value > 1) {
    currentLevel.value--;
    if (currentLevel.value === 1) {
      selectedGroup.value = null;
      selectedStore.value = null;
      selectedSite.value = null;
    } else if (currentLevel.value === 2) {
      selectedStore.value = null;
      selectedSite.value = null;
    }
  }
}

// 重置选择
function resetSelection() {
  selectedGroup.value = null;
  selectedStore.value = null;
  selectedSite.value = null;
  currentLevel.value = 1;
}

// 监听集团变化，重新加载门店
watch(selectedGroup, () => {
  if (selectedGroup.value) {
    StoreGrid.query();
  }
});

// 监听门店变化，重新加载站点
watch(selectedStore, () => {
  if (selectedStore.value) {
    SiteGrid.query();
  }
});
</script>

<template>
  <Modal 
    class="w-5/6" 
    :title="`三级切换 (Alt+KeyG) - 集团: ${currentInfo.group} | 门店: ${currentInfo.store} | 站点: ${currentInfo.site}`"
  >
    <Page auto-content-height>
      <!-- 当前选择信息 -->
      <div class="mb-4 p-4 bg-blue-50 rounded-lg">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-6">
            <div class="text-sm">
              <span class="text-gray-600">集团:</span>
              <span class="font-medium text-blue-600 ml-1">{{ currentInfo.group }}</span>
            </div>
            <div class="text-sm">
              <span class="text-gray-600">门店:</span>
              <span class="font-medium text-blue-600 ml-1">{{ currentInfo.store }}</span>
            </div>
            <div class="text-sm">
              <span class="text-gray-600">站点:</span>
              <span class="font-medium text-blue-600 ml-1">{{ currentInfo.site }}</span>
            </div>
          </div>
          <div class="flex gap-2">
            <button 
              v-if="currentLevel > 1" 
              @click="goBack"
              class="px-3 py-1 text-sm bg-gray-100 hover:bg-gray-200 rounded"
            >
              返回
            </button>
            <button 
              @click="resetSelection"
              class="px-3 py-1 text-sm bg-gray-100 hover:bg-gray-200 rounded"
            >
              重置
            </button>
            <button 
              @click="handleCompleteSwitch"
              :disabled="!selectedGroup || !selectedStore || !selectedSite"
              class="px-4 py-1 text-sm bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white rounded"
            >
              完成切换
            </button>
          </div>
        </div>
      </div>

      <!-- 集团选择 -->
      <div v-if="currentLevel === 1">
        <GroupGrid table-title="选择集团">
          <template #actions="{ row }">
            <TableAction
              :actions="[
                {
                  label: '选择此集团',
                  type: 'primary',
                  icon: ACTION_ICON.EDIT,
                  onClick: handleSelectGroup.bind(null, row),
                },
              ]"
            />
          </template>
        </GroupGrid>
      </div>

      <!-- 门店选择 -->
      <div v-if="currentLevel === 2">
        <StoreGrid table-title="选择门店">
          <template #actions="{ row }">
            <TableAction
              :actions="[
                {
                  label: '选择此门店',
                  type: 'primary',
                  icon: ACTION_ICON.EDIT,
                  onClick: handleSelectStore.bind(null, row),
                },
              ]"
            />
          </template>
        </StoreGrid>
      </div>

      <!-- 站点选择 -->
      <div v-if="currentLevel === 3">
        <SiteGrid table-title="选择站点">
          <template #actions="{ row }">
            <TableAction
              :actions="[
                {
                  label: '选择此站点',
                  type: 'primary',
                  icon: ACTION_ICON.EDIT,
                  onClick: handleSelectSite.bind(null, row),
                },
              ]"
            />
          </template>
        </SiteGrid>
      </div>
    </Page>
  </Modal>
</template>

<style scoped>
/* 可以添加一些自定义样式 */
</style>
